package com.yujing.yview

import android.app.Activity
import androidx.core.content.ContextCompat
import com.yujing.yview.base.YBaseDialog
import com.yujing.yview.databinding.DialogSetApiBinding

/**
 * 设置API
 * @author yujing 2021年5月19日11:24:19
 */
/*
用法：
val ySetIpDialog = SetApiDialog(this)
ySetIpDialog.setListener { api ->
    textView1.text = "API：$api"
    showSpeak("api")
}
ySetIpDialog.defaultApi = "/api/abc"
ySetIpDialog.show()
 */
class SetApiDialog(activity: Activity) : YBaseDialog<DialogSetApiBinding>(activity, R.layout.dialog_set_api) {

    init {
        fullscreen = true
        widthPixels = 0.4F
        heightPixels = 0.6F
        fillColor = ContextCompat.getColor(activity, R.color.fill_background)
    }

    private var listener: ((String?) -> Unit)? = null
    var btNameOK = "确　定"
    var btNameCancel = "取　消"
    var tvTitle = "设置服务API"
    var tvTips = "注意：请谨慎修改Api"
    var defaultApi: String? = null

    //文字大小比例
    var textSizeScale: Float = 1.0F

    //初始化完成
    var initCompleteListener: ((DialogSetApiBinding) -> Unit)? = null

    //确定事件
    private fun confirm() {
        val api: String = binding.etApi.text.toString()
        listener?.invoke(api)
    }

    override fun init() {
        //设置默认值
        if (defaultApi != null)
            binding.etApi.setText(defaultApi)
        binding.etApi.setSelection(binding.etApi.text.toString().length)
        binding.btConfirm.text = btNameOK
        binding.btCancel.text = btNameCancel
        binding.tvTitle.text = tvTitle
        binding.tvTips.text = tvTips
        //确定按钮监听
        binding.btConfirm.setOnClickListener {
            confirm()
        }
        //取消按钮监听
        binding.btCancel.setOnClickListener { dismiss() }
        //ip获取焦点
        view.post { binding.etApi.requestFocus() }

        //---------------------------缩放---------------------------
        binding.tvTitle.also { it.textSize = px2sp(it.textSize.toInt()) * textSizeScale }
        binding.etApi.also { it.textSize = px2sp(it.textSize.toInt()) * textSizeScale }
        binding.tvTips.also { it.textSize = px2sp(it.textSize.toInt()) * textSizeScale }

        //输入框高度缩放
        binding.etApi.also {
            val lp = it.layoutParams
            lp.height = (lp.height * textSizeScale).toInt()
            it.layoutParams = lp
        }
        //按钮高度缩放
        binding.llBt.also {
            val lp = it.layoutParams
            lp.height = (lp.height * textSizeScale).toInt()
            it.layoutParams = lp
        }
        //设置按钮文字大小
        binding.btCancel.also { it.textSize = px2sp(it.textSize.toInt()) * textSizeScale }
        binding.btConfirm.also { it.textSize = px2sp(it.textSize.toInt()) * textSizeScale }
        //---------------------------缩放---------------------------
        initCompleteListener?.invoke(binding)
    }

    fun setListener(listener: ((String?) -> Unit)?) {
        this.listener = listener
    }
}
